package com.sd.projectinterface;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import objects.CSProb;
import objects.Exp;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class AssignmentView extends Activity {
	
	TextView problemDisplay, solutionResponse;
    EditText userInput;
    Button checkInput;
    int userId, assignmentId, numProblems, currentProbNum;
    public static final String KEY_121 = "http://10.0.2.2/mathRomp/updateAssignmentScore.php";
    public static final String KEY_122 = "http://10.0.2.2/mathRomp/updatePercentage.php";
    public static final String KEY_123 = "http://10.0.2.2/mathRomp/updateCurrentProbNum.php";
	
	@Override
    protected void onCreate(Bundle savedInstanceState){
            super.onCreate(savedInstanceState);
            setContentView(R.layout.assignment_view);
            Bundle incoming = this.getIntent().getExtras();
            MyApplication myApp = (MyApplication) getApplicationContext();
            problemDisplay = (TextView) findViewById(R.id.problem);
            userInput = (EditText) findViewById(R.id.user_solution);
            checkInput = (Button) findViewById(R.id.check_input);
            solutionResponse = (TextView) findViewById(R.id.response);
            userId = incoming.getInt("userId");
            assignmentId = incoming.getInt("assignmentId");
            numProblems = incoming.getInt("numProblems");
            currentProbNum = incoming.getInt("currentProbNum");
            final String problems = incoming.getString("problems");
            
            if(currentProbNum == numProblems-1){
				checkInput.setText("Finish");
			}
            
        	JSONObject jObject;
        	JSONArray jArray = null;
        	JSONObject jObjectToProb = null;
        	final String[] templates = new String[numProblems];
			try {
				jObject = new JSONObject(problems);
				jArray = jObject.getJSONArray("problems");
				for(int i=0; i<templates.length; i++){
					templates[i] = jArray.getJSONObject(i).getString("currentProblem")+"";
				}
				problemDisplay.setText(templates[currentProbNum]);
				jObjectToProb = jArray.getJSONObject(currentProbNum);
				
			} catch (JSONException e) {
				System.out.println("Problem with jObject/jArray");
				problemDisplay.setText("Problem with jObject/jArray "+currentProbNum);
				e.printStackTrace();
			}
			
			final CSProb c = getProb(jObjectToProb);
			
			checkInput.setOnClickListener(new View.OnClickListener() {
				public void onClick(View arg0) {
					currentProbNum++;
					DecimalFormat df = new DecimalFormat("#.###");
                    Boolean correct = false;
                    
                    if(c.id == 0){
                            //Solution is an integer
                            System.out.println("c's id is 0");
                            double u = Double.parseDouble(userInput.getText()+"");
                            double r = Double.parseDouble(df.format(c.getSolution()));
                            if(u==r){
                                    correct = true;
                            }
                    }else if(c.id == 1){
                            //Solution is a fraction
                            System.out.println("c's id is 1");
                            String f = userInput.getText()+"";
                            f = f.replaceAll("\\s", "");
                            if(f.contains("/")){
                                    int i = f.indexOf("/");
                                    int n = Integer.parseInt(f.substring(0,i));
                                    int d = Integer.parseInt(f.substring(i+1, f.length()));
                                    System.out.println("n: "+n);
                                    System.out.println("d: "+d);
                                    if((n == c.getFSolution().num) && (d == c.getFSolution().denom)){
                                            correct = true;
                                    }
                            }else{
                                    double u = Double.parseDouble(userInput.getText()+"");
                                    System.out.println("Frac value: "+u);
                                    double r = Double.parseDouble(df.format(c.getFSolution().value()));
                                    if(u == r){
                                            correct = true;
                                    }
                            }
                    }else if(c.id == 2){
                            //Solution is an exponent
                            System.out.println("c's id is 2");
                            String e = userInput.getText()+"";
                            e = e.replaceAll(" ", "");
                            if(e.contains("^")){
                                    int i = e.indexOf("^");
                                    int n = Integer.parseInt(e.substring(0, i));
                                    int d = Integer.parseInt(e.substring(i+1, e.length()));
                                    System.out.println("n: "+n);
                                    System.out.println("e: "+e);
                                    if((n == c.getExpSolution().number) && (d == c.getExpSolution().exponent)){
                                            correct = true;
                                    }
                            }else{
                                    double u = Double.parseDouble(userInput.getText()+"");
                                    System.out.println("Expo value: "+c.getExpSolution().value());
                                    double r = Double.parseDouble(df.format(c.getExpSolution().value()));
                                    if(u == r){
                                            correct = true;
                                    }
                            }
                    }else if(c.id == 3){
                            //Solution is a list of factors
                            System.out.println("c's id is 3");
                            String in = userInput.getText()+"";
                            int[] f = c.getFactSolution();
                            if(f.length == 1){
                                    try{
                                     int u = Integer.parseInt(in);
                                     if(u == f[0]){
                                             correct = true;
                                     }
                                    }catch(NumberFormatException e){
                                           
                                    }
                             }else{
                                     int factorNum = 0;
                                     int charNum = 0;
                                     for(int i=0; i<f.length; i++){
                                             if((i==f.length-1) &&
                                                             (in.contains(", "+f[i]+"") || in.contains(","+f[i]+""))){
                                                     factorNum++;
                                             }else if(in.contains(""+f[i]+",")
                                                             || in.contains(""+f[i]+", ") || in.contains(""+f[i]+" ,")){
                                                     factorNum++;
                                             }
                                     }
                                     for(int i=0; i<in.length(); i++){
                                             if(in.charAt(i) == ','){
                                                     charNum++;
                                             }
                                     }
                                     if((factorNum == f.length) && (charNum == f.length-1)){
                                             correct = true;
                                     }
                             }
                    }else if(c.id == 4){
                            //Solution is a string
                            String u = (userInput.getText()+"").replace(" ", "");
                            String s;
                            for(int i=0; i<c.getPropSolution().length; i++){
                                    s = c.getPropSolution()[i].replace(" ", "");
                                    if(u.equals(s)){
                                            correct = true;
                                    }      
                            }
                    }else if(c.id == 5){
                    	//Solution is 2 roots
                    	int rootNum = 0;
                    	String in = userInput.getText()+"";
                    	double[] r = c.getRoots();
                    	if(in.contains(""+df.format(r[0])+",") || in.contains(", "+df.format(r[0])+"")){
                    		rootNum++;
                    	}
                    	if(in.contains(""+df.format(r[1])+",") || in.contains(", "+df.format(r[1])+"")){
                    		rootNum++;
                    	}
                    	if(rootNum == 2){
                    		correct = true;
                    	}
                    }else if(c.id == 6){
                    	String in = userInput.getText()+"";
                    	if(c.lineEquId == 0){
                    		String a = in.replaceAll(" ", "");
           				 	String s = c.getSlopeForm();
           				 	String p =s.replaceAll(" ", "");
           				 	if(p.equals(a)){
           				 		correct = true;
           				 	}
                    	}else if(c.lineEquId == 1){
           				 	String a = (in.replaceAll(" ", ""));
           				 	String s = (c.getGeneralForm().replaceAll(" ", ""));
           				 	s = s.trim();
           				 	System.out.println("a: "+a);
           				 	System.out.println("p: "+s);
           				 	if(s.equals(a)){
           				 		correct = true;
           				 	}
                    	}else if(c.lineEquId == 2){
                    		if(in.equals(df.format(c.getYIntercept()))){
                    			correct = true;
           				 	}
           			 	}else if(c.lineEquId == 3){
           			 		if(in.equals(df.format(c.getSlope()))){
           			 			correct = true;
           			 		}
           			 	}
                    }
           
                    if(correct){
                    		System.out.println(c.getProblem()+" solved correctly");
                            updateScore();
                    }
                    
                    updateProbNum();
					
					if(currentProbNum == numProblems){
						updatePercentage();
						Intent i = new Intent(AssignmentView.this, MyAssignments.class);
						i.putExtra("userId", userId);
						i.putExtra("assignmentId", assignmentId);
						i.putExtra("numProblems", numProblems);
						i.putExtra("currentProbNum", currentProbNum);
						i.putExtra("problems", problems);
						startActivity(i);
					}else{
						//problemDisplay.setText(templates[currentProbNum]);
						Intent i = new Intent(AssignmentView.this, AssignmentView.class);
						i.putExtra("userId", userId);
						i.putExtra("assignmentId", assignmentId);
						i.putExtra("numProblems", numProblems);
						i.putExtra("currentProbNum", currentProbNum);
						i.putExtra("problems", problems);
						startActivity(i);
					}
				}
			});
	}
	
	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
            getMenuInflater().inflate(R.menu.main, menu);
            return true;
    }
	
	public void updateScore(){
		//System.out.println("Updating score: aId="+assignmentId+" uId="+userId);
        InputStream is = null;
        String result = "";
        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("assignmentId", assignmentId+""));
        nameValuePairs.add(new BasicNameValuePair("userId", userId+""));
        
        //http post
        try{
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(KEY_121);
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                is = entity.getContent();
        }catch(Exception e){
                Log.e("log_tag", "Error in http connection in updateScore: "+e);
                return;
        }
       
        //convert response to string
        try{
                BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"),8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while((line = reader.readLine()) != null){
                        sb.append(line + "\n");
                }
                is.close();
                result = sb.toString();
                System.out.println(result);
        }catch(Exception e){
                Log.e("log_tag", "Error converting result updateScore: "+e);
                return;
        }
    }
	
	public void updatePercentage(){
		//System.out.println("Updating percentage: aId="+assignmentId+" uId="+userId);
        InputStream is = null;
        String result = "";
        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("assignmentId", assignmentId+""));
        nameValuePairs.add(new BasicNameValuePair("userId", userId+""));
        
        //http post
        try{
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(KEY_122);
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                is = entity.getContent();
        }catch(Exception e){
                Log.e("log_tag", "Error in http connection in updateScore: "+e);
                return;
        }
        
        try{
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"),8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while((line = reader.readLine()) != null){
                    sb.append(line + "\n");
            }
            is.close();
            result = sb.toString();
            System.out.println(result);
        }catch(Exception e){
            Log.e("log_tag", "Error converting result updateScore: "+e);
            return;
        }
	}
	
	public void updateProbNum(){
		//System.out.println("Updating percentage: aId="+assignmentId+" uId="+userId);
        InputStream is = null;
        String result = "";
        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("assignmentId", assignmentId+""));
        nameValuePairs.add(new BasicNameValuePair("userId", userId+""));
        nameValuePairs.add(new BasicNameValuePair("currentProbNum", currentProbNum+""));
        
        //http post
        try{
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(KEY_123);
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                is = entity.getContent();
        }catch(Exception e){
                Log.e("log_tag", "Error in http connection in updateScore: "+e);
                return;
        }
        
        try{
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"),8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while((line = reader.readLine()) != null){
                    sb.append(line + "\n");
            }
            is.close();
            result = sb.toString();
            System.out.println(result);
        }catch(Exception e){
            Log.e("log_tag", "Error converting result updateScore: "+e);
            return;
        }
	}
	
	public CSProb getProb(JSONObject prob){
		if(prob == null){
			return null;
		}
		int probId;
		try {
			probId = prob.getInt("id");
			System.out.println("prob.id: "+probId);
			if(probId == 0){
				return new CSProb(prob.getString("currentProblem"), prob.getDouble("solution"));
			}else if(probId == 1){
				return new CSProb(prob.getString("currentProblem"), prob.getInt("fracSolutionNum"), prob.getInt("fracSolutionDenom"));
			}else if(probId == 2){
				return new CSProb(prob.getString("currentProblem"), new Exp(prob.getInt("expSolutionNum"), prob.getInt("expSolutionExp")));
			}else if(probId == 3){
				JSONArray jsonFactors = prob.getJSONArray("factSolution");
				int[] factors = new int[jsonFactors.length()];
				for(int i=0; i<factors.length; i++){
					factors[i] = jsonFactors.getJSONObject(i).getInt("factor");
				}
				return new CSProb(prob.getString("currentProblem"), factors);
			}else if(probId == 4){
				JSONArray jsonProps = prob.getJSONArray("propSolution");
				String[] props = new String[jsonProps.length()];
				for(int i=0; i<props.length; i++){
					props[i] = jsonProps.getJSONObject(i).getString("prop");
				}
				return new CSProb(prob.getString("currentProblem"), props);
			}else if(probId == 5){
				double r[] = {prob.getDouble("root1"), prob.getDouble("root2")};
				return new CSProb(prob.getString("currentProblem"), r);
			}else if(probId == 6){
				return new CSProb(prob.getString("currentProblem"), prob.getString("slopeIntForm"), prob.getString("genForm"), prob.getDouble("yInt"), prob.getDouble("slope"), prob.getInt("lineEquId"));
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return null;
    }
}